package cn.itsource.mq._01_helloword;

import cn.itsource.mq.util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
/**
 * @description: 消费者
 */
public class ConsumerTest {
    //队列名称
    public static final String QUEUE_HELLOWORD = "helloworld";
    /**
     * 步骤：
     * 1、创建连接
     * 2、创建信道
     * 3、监听队列
     * 4、处理消息
     */
    public static void main(String[] args) throws Exception {
//        //定义连接工厂
//        ConnectionFactory factory = new ConnectionFactory();
//        //设置服务地址
//        factory.setHost("localhost");
//        //1、创建连接，通过工厂获取连接
//        Connection connection = factory.newConnection();
        Connection connection = ConnectionUtil.getConnection();
        //2、创建信道
        Channel channel = connection.createChannel();
        //3、监听队列(接收消息)
        channel.basicConsume(QUEUE_HELLOWORD, false, new DefaultConsumer(channel){
            //4、处理消息
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("我是消费者Consumer1，收到消息：" + new String(body)+1/0);
                channel.basicAck(envelope.getDeliveryTag(),false);
//                //消费者标签
//                System.out.println("consumerTag=" + consumerTag);
//                //交换机
//                System.out.println("getExchange=" + envelope.getExchange());
//                //路由key
//                System.out.println("getRoutingKey=" + envelope.getRoutingKey());
//                //消息ID
//                System.out.println("getDeliveryTag=" + envelope.getDeliveryTag());
            }
        });
    }
}